<!--测试题目：答题页-->
<template>
	<view class="content bg-color">

		<view v-if="testData">

			<view class="top-pnl">
				<view class="progress-box">
					<progress :percent="computedPercent"
							  border-radius="10rpx"
							  stroke-width="20rpx"
							  font-size="28rpx"
							  activeColor="#8A2BE2"
							  backgroundColor="#EBEBEB"
							  active="true"
							  active-mode="forwards"
							  duration="30"
					/>
					<view class="progress-show-rate">{{computedPercent}}%</view>
				</view>
				<view class="main-tip"><text class="curr-num">{{currIndex+1}}</text>/{{totalNum}}</view>
				<view class="btn-pre" v-if="currIndex>0" @click="onClickPre">上一题</view>
			</view>

			<view class="top-gra"></view>

			<view>

				<swiper :autoplay="false"
						:circular="true"
						:current="swiperIndex"
						duration="500"
						class="test-swiper"
						@change="onSwiperChange"
						@animationfinish="onSwiperAnimaEnd"
				>
					<swiper-item v-for="(item,index) in showList" :key="index" class="test-swiper-item">

						<view v-if="item._id">
							<!--题目-->
							<view v-if="item.t">
								<view v-if="item.t.txt" class="title-txt">{{item.t.txt}}</view>
								<image v-if="item.t.img" class="title-img" mode="widthFix">{{item.t.img}}</image>
							</view>

							<!--选项-->
							<view v-for="(select,ii) in item.a" :key="ii">
								<view v-if="select.type==='txt'" class="select-txt"  :class="computedSelect(item.index,select.index)?'select-txt-s':''"  @click="onClickSelect(item.index,select.index)" >{{computedAIndex(ii)}}{{select.content}}</view>
								<view v-if="select.type==='img'">
									<view>{{computedAIndex(ii)}}</view>
									<image :src="select.url"></image>
								</view>
							</view>

						</view>
					</swiper-item>
				</swiper>

			</view>

		</view>

		<!--答题结束后出现查看结果按钮，点击跳转到结果分析页面-->
		<!--<view>查看结果</view>-->
		<view class="result-pnl" v-if="computedPercent===100">
			<button v-if="computedPayType===1" class="btn-result" :loading="loading" @click="onClickResult">查看测试结果</button>
			<button v-if="computedPayType===2" class="btn-result" @click="onClickVideo">看激励视频生成结果分析</button>
			<button v-if="computedPayType===3" class="btn-result" @click="onClickPay">支付{{computedShowPayValue}}生成结果分析</button>
		</view>
	</view>
</template>

<script>

	let dataList=[];//所有题目数据列表

	import {shareConfigDefault,shareConfig,updateShareConfig} from "@/utils/share";
	import { mapActions, mapState ,mapGetters} from 'vuex'
	export default {
		components: {},

		data() {
			return {

				loading:false,
				timer:null,//延时器
				testId:0,

				showList:[//显示列表

				],

				currIndex:0,//数据索引
				swiperIndex:0,//swiper索引

				totalNum:0,

				userAnswers:[],//用户选择的答案索引
				//autoSwiper:false,//选择后自动滑动
				targetIndex:0, //目标移动索引

				scores:0

				//判断当前设备类型
			}
		},
		onLoad(e) {
			wx.showShareMenu({
				withShareTicket:true,
				menus:['shareAppMessage','shareTimeline']
			})

			if(this.testData){
				this.initView();
			}

		},
		destroyed(){
			if(this.timer){
				clearInterval(this.timer);
				this.timer=null;
			}
		},
		onShareAppMessage(res){
			updateShareConfig({
				title:this.testData.title,
				desc: this.testData.title,
				path: '/pages/main/start?backflow=true&uid='+this.testId,
			});
			return shareConfig;
		},
		computed:{

			//当前的支付模式 1免费 2视频激励 3支付
			computedPayType(){
				if(this.computedIsIos&&this.testData.pay){
					return this.testData.pay.ios;
				}else if(!this.computedIsIos&&this.testData.pay){
					return this.testData.pay.other;
				}else{
					return 2;
				}
			},

			//需要支付XX分
			computedPayValue(){
				if(this.testData.pay){
					return this.testData.pay.value;
				}
				return 0
			},

			computedShowPayValue(){
				let str=(this.computedPayValue/100.0).toFixed(2)+'元';
				return str;
			},


			//是否ios设备
			computedIsIos(){
				if(this.systemInfo){
					let system=this.systemInfo.system.toLowerCase();
					if(system.indexOf('ios')!=-1){
						return true;
					}
				}
				return false
			},

			//判断当前项是否选中
			computedSelect(){
				return function (index,i) {
					console.log('index:'+index,'i:'+i);
					if(this.userAnswers[index]===i+1){
						return true;
					}
					return false
				}
			},
			computedPercent(){
				let finish=0;
				for(let i=0;i<this.userAnswers.length;i++){
					if(this.userAnswers[i]&&this.userAnswers[i]>0){
						finish++
					}
				}

				let percent=Math.floor(100*finish/this.totalNum);
				return percent;
			},

			/*选项标号显示*/
			computedAIndex(){
				return function (ii) {
					if(ii===0){
						return 'A、'
					}else if(ii===1){
						return 'B、'
					}else if(ii===2){
						return 'C、'
					}else if(ii===3){
						return 'D、'
					}else if(ii===4){
						return 'E、'
					}else if(ii===5){
						return 'F、'
					}else if(ii===6){
						return 'G、'
					}
				}
			},

			...mapState(['isInit','systemInfo']),
			...mapState('server',['testData']),

		},
		methods: {

			clearData(){
				this.currIndex=0;//数据索引
				this.swiperIndex=0;//swiper索引
				this.totalNum=0;
				this.targetIndex=0; //目标移动索引
				this.scores=0;

				dataList=[];
				this.showList=[];
				this.userAnswers=[];//用户选择的答案索引
			},

			async initView(){

				this.clearData();

				dataList=dataList.concat(this.testData.question);//题目列表
				// dataList=dataList.concat({end:this.testData.result});

				if(dataList.length>3){
					this.showList=[dataList[0],dataList[1],dataList[dataList.length-1]];
				}else{
					this.showList=dataList;
				}

				this.totalNum=this.testData.question.length;
			},

			onSwiperAnimaEnd(e){

				if(dataList.length<=3){
					return;
				}

				//更新swiper索引
				let newCurrent=e.detail.current;
				let oldCurrent=this.swiperIndex; //只是用来判断数据变动方向

				if(newCurrent===oldCurrent) { //自动滑动到指定位置
					//console.log('e.detail:'+JSON.stringify(e.detail))
					//更新到当前状态
					this.currIndex=this.targetIndex;
					let nextIndex=this.currIndex===dataList.length-1?0:this.currIndex+1;
					let preIndex=this.currIndex===0?(dataList.length-1):this.currIndex-1;

					let showItems=[
						dataList[preIndex],
						dataList[this.currIndex],
						dataList[nextIndex]
					]

					this.updateShowList(showItems);
					return;
				}

				this.swiperIndex=newCurrent;

				//更新数据索引
				if(newCurrent===oldCurrent+1||oldCurrent+1===this.showList.length+newCurrent){//正向
					console.log('正向')
					this.currIndex++;
				}else{//逆向
					console.log('逆向')
					this.currIndex--;
				}

				//数据索引边界处理
				if(this.currIndex>dataList.length-1){
					this.currIndex=0;
				}else if(this.currIndex<0){
					this.currIndex=dataList.length-1;
				}

				let currIndex=this.currIndex;
				let nextIndex=this.currIndex===dataList.length-1?0:this.currIndex+1;
				let preIndex=this.currIndex===0?(dataList.length-1):this.currIndex-1;

				let showItems=[
					dataList[preIndex],
					dataList[currIndex],
					dataList[nextIndex]
				]

				this.updateShowList(showItems);


			},

			onSwiperChange(e){
				//console.log('swiper-change-e:'+JSON.stringify(e))

			},

			//取得目标索引:优先 下一个未答题目，其次第一个未答题目
			getTargetIndex(){
				let _index=this.currIndex;
				for(let i=0;i<dataList.length;i++){
					_index=_index+1;
					if(_index>dataList.length-1){
						_index=0;
					}
					if(!this.userAnswers[_index]){//没有选择
						return _index;
						break;
					}
				}
				return dataList.length-1;
			},

			onClickSelect(index,i){
				//console.log('题目索引：'+index);
				//console.log('select-i:'+JSON.stringify(i));

				//当前题目做出选择
				this.$set(this.userAnswers,index,(i+1));

				//this.userAnswers[index]=i+1;
				//更新顶部答题进度
				//选中之后 更新到目标位置的上一个状态，然后动画切换到目标状态

				//this.autoSwiper=true;

				//当前位置
				//this.currIndex;

				if(this.computedPercent===100){
					return;
				}

				//目标位置  优先 下一个未答题目，其次第一个未答题目
				let targetIndex=this.getTargetIndex();
				this.scrollToTargetIndex(targetIndex);
				//　如果完成所有题目，底部显示查看结果按钮

			},


			//控制滚到到指定索引位置
			scrollToTargetIndex(targetIndex){

				this.targetIndex=targetIndex;

				if(targetIndex>this.currIndex){//正向翻

					let preIndex=this.currIndex>0?this.currIndex-1:(dataList.length-1);
					let preItem=dataList[preIndex];
					let currItem=dataList[this.currIndex];
					let nextItem=dataList[targetIndex];

					this.updateShowList([preItem,currItem,nextItem])

					if(this.swiperIndex<2){
						this.swiperIndex=this.swiperIndex+1;
					}else{
						this.swiperIndex=0
					}

				}else{//逆向翻

					let preItem=dataList[targetIndex];
					let currItem=dataList[this.currIndex];
					let nextIndex=this.currIndex<dataList.length-1?this.currIndex+1:0;
					let nextItem=dataList[nextIndex];

					this.updateShowList([preItem,currItem,nextItem])

					if(this.swiperIndex>0){
						this.swiperIndex=this.swiperIndex-1;
					}else{
						this.swiperIndex=this.showList.length-1;
					}
				}


			},

			//根据指定数据index更新显示
			updateShowList(items){
				let pre=items[0];
				let curr=items[1];
				let next=items[2];

				//当前item不用处理，其他两个item更新显示；
				if(this.swiperIndex===0){
					this.$set(this.showList,0,curr);//
					this.$set(this.showList,1,next);
					this.$set(this.showList,2,pre);
				}else if(this.swiperIndex===1){
					this.$set(this.showList,0,pre);
					this.$set(this.showList,1,curr);//
					this.$set(this.showList,2,next);
				}else if(this.swiperIndex===2){
					this.$set(this.showList,0,next);
					this.$set(this.showList,1,pre);
					this.$set(this.showList,2,curr);//
				}
			},


			onClickVideo(){

			},


			onClickPay(){

			},

			//取得总得分
			getTotalScores(){
				let total=0;
				for(let i=0;i<dataList.length;i++){
					let answerIndex=this.userAnswers[i]-1;
					let score=dataList[i].a[answerIndex].score;
					total+=score;
				}
				return total;
			},
			async onClickResult(){

				if(this.loading)return;
				this.loading=true;

				//保存用户数据并返回分析结果
				let answers=this.userAnswers;
				let scores=this.getTotalScores();//得分
				let testId=this.testData._id;


				let params={
					answers:answers,
					scores:scores,
					testId:testId
				}

				console.log('params:'+JSON.stringify(params));
				let result=await this.saveResult(params);
				console.log('result:'+JSON.stringify(result));
				this.loading=false;
				if(result&&result.code===200){
					uni.navigateTo({url:'/pages/main/result'})
				}else{
					uni.showToast({title:'服务异常',icon:'none'});
				}
			},

			/*上一题*/
			onClickPre(){
				this.scrollToTargetIndex(this.currIndex-1);
			},

			...mapActions('server',['saveResult']),
		}
	}
</script>

<style>

	.top-pnl{
		height: 100upx;
	}
	.top-gra{
		height: 20upx;
		background-color: #f1f1f1;
	}

	.test-title{
		font-size: 48upx;
		padding: 30upx;
		height: 50upx;
		line-height: 50upx;
		color: #000000;
	}

	.start-item{
		margin: 30upx;
		color: #c8c7cc;
		font-size: 26upx;
	}

	.start-btn{
		margin: 30upx;
		height: 80upx;
		background-color: #f07534;
		color: white;
		border-radius: 10upx;
		font-size: 28upx;
	}

	.start-btn:after{
		border: 0;
	}

	.title-txt{
		font-size: 32upx;
		margin: 30upx;
	}

	.title-img{
		margin: 30upx;
	}

	.select-txt{
		margin: 30upx;
		padding: 20upx;
		min-height: 30upx;
		background-color: #f1f1f1;
		color: #555555;
		font-size: 28upx;
		border-radius: 35upx 35upx;
	}

	.select-txt-s{
		background-color: rgb(142, 52, 244);
		color: white;
	}

	.main-tip{
		position: absolute;
		padding: 0 30upx;
		width: 100upx;
		height: 100upx;
		line-height: 100upx;
		color: rgba(0,0,0,0.3);
		top:0;
		right: 0;
		font-size: 28upx;
		text-align: right;
	}

	.curr-num{
		font-size: 32upx;
		color: #333333;
	}

	.progress-box{
		position: relative;
		height: 20upx;
		padding: 40upx 230upx;
	}
	.progress-show-rate{
		position: absolute;
		right: 100upx;
		top:0;
		width: 100upx;
		height: 100upx;
		line-height: 100upx;
	}
	.btn-pre{
		position: absolute;
		width: 100upx;
		height: 40upx;
		line-height: 40upx;
		border: 1px solid #8A2BE2;
		color: #8A2BE2;
		left: 30upx;
		top:30upx;
		font-size: 28upx;
		text-align: center;
		border-radius: 20upx 20upx;
	}

	.test-swiper{
		height: 80vh;
	}

	.result-pnl{
		position: fixed;
		width: 690upx;
		height: 90upx;
		padding: 30upx;
		bottom: 0;
		text-align: center;
	}

	.btn-result{
		width: 100%;
		height: 90upx;
		line-height: 90upx;
		border-radius: 40upx;
		color: white;
		font-size: 32upx;
		background-color: #ff7070;
	}

	.btn-result:after{
		border: 0;
	}

</style>
